package com.cychat.mall.consumer;

import com.Cychat.commons.entity.pojo.OrderDetail;
import com.Cychat.commons.entity.pojo.Orders;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cychat.mall.mapper.OrderDetailMapper;
import com.cychat.mall.mapper.OrdersMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-11-8:下午 3:10  <br/>
 * Description: 订单超时消费者
 */
@Component
public class OrderTimeoutConsumer {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queues = "order.release.queue")
    @Transactional(rollbackFor = Exception.class)
    public void handleOrderTimeout(String orderId) {
        Orders order = ordersMapper.selectById(orderId);
        if (order == null || !"0".equals(order.getOrderStatus().toString())) {
            return; // 已支付或已处理
        }

        // 更新订单状态为“超时”, 4 = 超时
        ordersMapper.update(order, new LambdaUpdateWrapper<Orders>()
                .set(Orders::getOrderStatus, 4)
                .eq(Orders::getOrderId, orderId));

        // 查询订单详情，回滚 Redis 库存
        for (OrderDetail detail : orderDetailMapper.selectList(
                new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderId))) {
            stringRedisTemplate.opsForValue().increment("stock:" + detail.getProductId(), detail.getQuantity());
        }
    }
}
